<?php

namespace App\Repositories\MoneyCard;

use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\MoneyCard\CardCouponsRepository;
use App\Models\MoneyCard\CardCoupons;
use App\Validators\MoneyCard\CardCouponsValidator;

/**
 * 卡券列表
 * Class CardCouponsRepositoryEloquent
 * @package namespace App\Repositories\MoneyCard;
 */
class CardCouponsRepositoryEloquent extends BaseRepository implements CardCouponsRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return CardCoupons::class;
    }

    /**
     * 查询卡券信息
     * @param string $cardSn
     * @return bool|mixed
     */
    public function getCardCouponsInfo(string $cardSn){
        $where = ['card_sn'=>$cardSn];

        $CardInfo = $this->findWhere($where,['id','user_id','use_time','state']);
        if($CardInfo){
            return $CardInfo;
        }else{
            return false;
        }
    }

    /**
     * 使用卡券
     * @param int $cardId
     * @param int $userId
     * @return mixed
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function useCardCoupons(int $cardId ,int $userId){
        $data['user_id'] =  $userId;    //用户ID
        $data['use_time'] = gm_time();   //使用时间 格林威治时间
        $data['state'] = 2;             //标记为已使用
        return $this->update($data,$cardId);
    }


    public function countCardUsed(int $cardClass,int $userId){
        $where['card_class'] = $cardClass;
        $where['user_id'] = $userId;
        return $this->where($where)->count();
    }
    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }
}
